package com.lanniao.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanniao.constant.MessageConstant;
import com.lanniao.dto.PageQueryDto;
import com.lanniao.dto.UserLoginDto;
import com.lanniao.entity.TbUser;
import com.lanniao.exception.AccountNotFoundException;
import com.lanniao.exception.PasswordErrorException;
import com.lanniao.mapper.UserMapper;
import com.lanniao.result.PageResult;
import com.lanniao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public TbUser login(UserLoginDto user) {
        //获取用户名和密码
        String username = user.getUsername();
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        System.out.println(password);
        TbUser user1 = userMapper.getByUsername(username);
        if (user1 == null){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if (!password.equals(user1.getPassword())){
            throw new PasswordErrorException((MessageConstant.PASSWORD_ERROR));
        }
        user1.setPassword(null);
        return user1;
    }

    @Override
    public TbUser getById(Integer id) {
        TbUser user = userMapper.getById(id);
        return user;
    }

    @Override
    public PageResult pageQuery(PageQueryDto pageQueryDto) {
        PageHelper.startPage(pageQueryDto.getPage(), pageQueryDto.getPageSize());
        Page<TbUser> page = userMapper.selectAll(pageQueryDto);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void update(TbUser tbUser) {
        userMapper.update(tbUser);
    }
}
